package io.ouka.jvm.hotspot.selfread.read;


import io.ouka.jvm.hotspot.selfread.InstanceKlass;
import io.ouka.jvm.hotspot.selfread.constant.FinalConstant;
import io.ouka.jvm.hotspot.selfread.domain.ConstantPool;
import io.ouka.jvm.hotspot.selfread.util.DataTranslate;

/**
 * @author Ouka
 */
public class ConstantPoolReader extends AbstractReader {


    public ConstantPoolReader() {
        this.iReader = new AccessFlagsReader();
    }

    private int size;

    @Override
    public void preRead(byte[] content) {
        byte[] sizeByte = new byte[FinalConstant.u2];
        System.arraycopy(content, index, sizeByte, 0, FinalConstant.u2);
        this.size = DataTranslate.byteToUnsignedShort(sizeByte);
        index += FinalConstant.u2;
        byte[] constantPoolByte = new byte[content.length - index];
        System.arraycopy(content, index, constantPoolByte, 0, content.length - index);
        this.selfContent = constantPoolByte;
    }

    @Override
    public void read() {
        instanceKlass.setConstantPool(parseConstantPool());
    }

    private ConstantPool parseConstantPool() {
        ConstantPool constantPool = new ConstantPool();
        constantPool.setLength(size);
        constantPool.setIndex(selfContent);
        constantPool.parse();
        return constantPool;
    }
}
